<template>
  <div class="cart-container">
    <PageHeader title="购物车" :show-back="false" />

    <!-- 购物车为空 -->
    <div class="empty-cart" v-if="cartStore.cartItems.length === 0">
      <van-empty image="error" description="购物车还是空的">
        <van-button round type="primary" class="go-shopping" @click="goToProduct">去选购商品</van-button>
      </van-empty>
    </div>

    <!-- 购物车列表 -->
    <div class="cart-list" v-else>
      <template v-if="cartStore.priceUpdateInfo.status === 'changed'">
        <div class="cart-refresh warning">
          <span>商品价格已更新</span>
          <span class="price-update-info">价格变化，请检查</span>
        </div>
      </template>
      <template v-else-if="cartStore.priceUpdateInfo.isUpdating">
        <div class="cart-refresh updating">
          <span>正在更新商品价格...</span>
          <van-loading type="spinner" size="16px" />
        </div>
      </template>
      <template v-else>
        <div class="cart-refresh" v-if="isOldPrices">
          <span>数据可能不是最新</span>
          <van-button
            type="primary"
            size="mini"
            plain
            @click="refreshPrices"
            :loading="refreshing"
          >刷新价格</van-button>
        </div>
      </template>
      <van-swipe-cell
        v-for="item in cartStore.cartItems"
        :key="item.id"
        :before-close="beforeClose"
      >
        <div class="cart-item">
          <div class="item-selector">
            <van-checkbox
              :value="item.checked"
              @click="toggleChecked(item.id, !item.checked)"
              icon-size="16"
            />
          </div>
          <div class="item-image" @click="goToProductDetail(item.id)">
            <img :src="item.image" :alt="item.name" />
          </div>
          <div class="item-info">
            <div class="item-name" @click="goToProductDetail(item.id)">{{ item.name }}</div>
            <div v-if="item.skuSpecs" class="item-specs">
              <span v-for="(value, key) in item.skuSpecs" :key="key">{{ key }}: {{ value }}</span>
            </div>
            <div class="item-price">{{ item.price }} 积分</div>
            <div class="item-actions">
              <van-stepper
                v-model="item.quantity"
                integer
                :min="1"
                :max="item.stock"
                :disabled="!item.checked"
                @change="updateQuantity(item.id, item.quantity)"
              />
            </div>
          </div>
        </div>

        <template #right>
          <van-button
            square
            text="删除"
            type="danger"
            class="delete-button"
            @click="removeItem(item.id)"
          />
        </template>
      </van-swipe-cell>
    </div>

    <!-- 底部结算栏 -->
    <div class="submit-bar" v-if="cartStore.cartItems.length > 0">
      <div class="select-all">
        <van-checkbox
          :value="cartStore.isAllChecked"
          @click="toggleAll(!cartStore.isAllChecked)"
          icon-size="16"
        >全选</van-checkbox>
      </div>
      <div class="total">
        <div>
          合计:
          <span class="price">{{ cartStore.checkedTotal }}</span> 积分
        </div>
        <div class="small">已选 {{ cartStore.checkedCount }} 件商品</div>
      </div>
      <div class="submit">
        <van-button
          type="danger"
          :disabled="cartStore.checkedCount === 0"
          @click="goToCreateOrder"
        >结算</van-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'
import { showDialog, showSuccessToast, showFailToast } from 'vant'
import PageHeader from '@/components/PageHeader.vue'
import { useCartStore } from '@/stores/cart'
import { useUserStore } from '@/stores/user'
import { ref, computed } from 'vue'

const router = useRouter()
const cartStore = useCartStore()
const userStore = useUserStore()
const refreshing = ref(false)

// 判断价格是否需要更新（超过10分钟）
const isOldPrices = computed(() => {
  const lastUpdateTime = cartStore.priceUpdateInfo.lastUpdateTime
  return Date.now() - lastUpdateTime > 10 * 60 * 1000 // 10分钟
})

// 切换商品选中状态
const toggleChecked = (id: number, checked: boolean) => {
  cartStore.updateChecked(id, checked)
}

// 更新商品数量
const updateQuantity = (id: number, quantity: number) => {
  cartStore.updateQuantity(id, quantity)
}

// 全选/取消全选
const toggleAll = (checked: boolean) => {
  cartStore.toggleCheckAll(checked)
}

// 删除确认
const beforeClose = ({
  position,
  instance,
}: {
  position: string
  instance: any
}) => {
  // 右侧按钮点击
  if (position === 'right') {
    showDialog({
      title: '确定删除此商品？',
      message: '删除后不可恢复',
      showCancelButton: true,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })
      .then(() => {
        instance.close()
      })
      .catch(() => {
        instance.close()
      })

    return false
  }

  return true
}

// 删除商品
const removeItem = (id: number) => {
  cartStore.removeFromCart(id)
}

// 前往商品详情
const goToProductDetail = (id: number) => {
  router.push(`/product/${id}`)
}

// 前往商品列表
const goToProduct = () => {
  router.push('/product')
}

// 前往订单创建页面
const goToCreateOrder = async () => {
  // 检查是否登录
  if (!userStore.isLoggedIn) {
    showDialog({
      title: '提示',
      message: '请先登录后再结算',
      confirmButtonText: '去登录',
    }).then(() => {
      router.push({
        path: '/login',
        query: { redirect: '/cart' },
      })
    })
    return
  }

  try {
    // 验证并获取最新价格的商品
    await cartStore.refreshCartPrices()
    router.push('/order/create')
  } catch (error) {
    console.error('结算前验证价格失败:', error)
  }
}

// 刷新价格
const refreshPrices = async () => {
  if (refreshing.value) return

  refreshing.value = true
  try {
    await cartStore.refreshCartPrices() // 移除强制刷新参数
    showSuccessToast('价格已更新')
  } catch (error) {
    console.error('刷新价格失败:', error)
    showFailToast('刷新价格失败')
  } finally {
    refreshing.value = false
  }
}
</script>

<style scoped lang="scss">
.cart-container {
  min-height: 100vh;
  background-color: $background-color;
  padding-bottom: 50px;
}

.empty-cart {
  padding-top: 100px;

  .go-shopping {
    margin-top: $padding-md;
  }
}

.cart-list {
  padding: $padding-xs;
  margin-bottom: 50px;
}

.cart-refresh {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff7e6;
  padding: $padding-sm $padding-md;
  margin-bottom: $padding-xs;
  border-radius: $border-radius-sm;
  font-size: $font-size-sm;
  color: $warning-color;

  &.warning {
    background-color: #ffece8;
    color: $danger-color;
  }

  &.updating {
    background-color: #ecf9ff;
    color: $primary-color;
  }

  .price-update-info {
    font-size: $font-size-xs;
  }
}

.cart-item {
  display: flex;
  background-color: $white;
  padding: $padding-md;
  border-radius: $border-radius-md;

  .item-selector {
    display: flex;
    align-items: center;
    margin-right: $padding-sm;
  }

  .item-image {
    width: 80px;
    height: 80px;
    margin-right: $padding-md;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      border-radius: $border-radius-sm;
    }
  }

  .item-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .item-name {
      font-size: $font-size-md;
      color: $text-color;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      margin-bottom: $padding-xs;
    }

    .item-specs {
      font-size: $font-size-sm;
      color: $text-color-light;
      margin-bottom: $padding-xs;
    }

    .item-price {
      font-size: $font-size-md;
      color: $danger-color;
      font-weight: 500;
      margin-bottom: $padding-sm;
    }

    .item-actions {
      display: flex;
      justify-content: flex-end;
    }
  }
}

.delete-button {
  height: 100%;
}

.submit-bar {
  position: fixed;
  bottom: 50px;
  left: 0;
  right: 0;
  height: 50px;
  background-color: $white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 $padding-md;
  box-shadow: 0 -1px 10px rgba(0, 0, 0, 0.05);

  .select-all {
    flex: 0 0 auto;
  }

  .total {
    flex: 1;
    padding: 0 $padding-md;

    .price {
      color: $danger-color;
      font-weight: 500;
    }

    .small {
      font-size: $font-size-sm;
      color: $text-color-light;
    }
  }

  .submit {
    flex: 0 0 auto;

    .van-button {
      height: 40px;
      font-size: $font-size-md;
      border-radius: $border-radius-max;
    }
  }
}
</style> 